package com.example.demo.alex.filter;

import com.example.demo.alex.model.Resource;
import com.example.demo.alex.model.Role;
import com.example.demo.alex.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * @ClassName FilterInvocationSecurityMetadataSourceImpl
 * @Description TODO
 * @Author zjg
 * @Date 2018/12/2518:07
 * @Version 2.0
 */
@Component
public class FilterInvocationSecurityMetadataSourceImpl implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private ResourceService resourceService;

    @Override
    //接收用户请求的地址，返回访问该地址需要的所有权限
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
    String requestUrl=((FilterInvocation)o).getRequestUrl();
        System.out.println("请求的地址"+requestUrl);
        //如果登录页面不需要权限
        if("/login".equals(requestUrl)){
            return null;
        }
        Resource resource=resourceService.getResourceByUrl(requestUrl);
        //如果没有匹配的url则说明大家可以访问
        if(resource==null){
            return SecurityConfig.createList("ROLE_LOGIN");
        }
        //将resource所需要的roles按封装要求返回
        List<Role> roles= resourceService.getRoles(resource.getId());
        int size=roles.size();
        String[] values=new String[size];
        for (int i=0;i<size;i++){
            values[i]=roles.get(i).getRoleName();
        }
        return SecurityConfig.createList(values);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
